import { getUserProfile, navigateTo, setClipboardData, showModal } from "../../utils/asyncWx.js";
import { insert, search, callFunction } from "../../utils/cloud.js";
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    wxid:"Aboy1918",
  },
    onLoad () {
    let userInfo = wx.getStorageSync("userInfo") || [];
    this.setData({ userInfo});
  },
  onShow() {
      let userInfo = wx.getStorageSync("userInfo") || [];
      this.setData({ userInfo });
      app.data.type = "common";
  },
  /**
   * 未登录点击按钮触发事件 ,并将数据上传到云端
   */
  async handlegetUserProfile() {
      let { userInfo } = await getUserProfile({ desc: "获取用户信息" });
      if (userInfo.nickName == null) {
          return
      }
      const { result } = await callFunction({ name: "login" });
      
      wx.setStorageSync("userInfo", ({
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          openid: result.openid,
      }));
      
      this.setData({
          userInfo: {
              nickName: userInfo.nickName,
              avatarUrl: userInfo.avatarUrl,
              openid: result.openid,
          }
      });
      const { data } = await search({
          table: "user",
          openid: result.openid,
      });
    //   如果不存在,则添加用户数据
      if (data.length === 0) {
        //   console.log("添加成功");
        insert({
            table: "user",
            data: {
                nickName: userInfo.nickName,
                avatarUrl: userInfo.avatarUrl,
            },
        });
      }
  },
  async handlelogout(){
    let res = await showModal({ content: "您确定要注销吗？该操作不会清除日记缓存。" });
    if(res.confirm){
      var userInfo=[];
      wx.setStorageSync('userInfo', userInfo);
      this.onShow();
    }else{
      return;
    }
    },
  /**
   * 置空日记数据
   * @returns 
   */
    async handleempty () {
        if (this.data.userInfo.nickName == null) {
            return;
      }
    let res = await showModal({ content: "您确定要清空所有日记数据吗？" });
      if (res.confirm) {
          res = await showModal({ content: "此操作无法撤销，请您再次确定是否清空" });
          if (res.confirm) {
              var diary = [];
              callFunction({ name: "batchDelete" });
              wx.setStorageSync('diary', diary);
          } else {
              return;
          }
      } else {
          return;
      }
    },
    /**
     * 点击复制粘贴数据
     */
    handleCopy () {
        setClipboardData({ data: this.data.wxid });
    },

    handleAbout () {
        navigateTo({
            url: "../aboutme/aboutme",
        });
    },
});